import * as echarts from 'echarts/core'
import {
  TooltipComponent,
  type TooltipComponentOption,
  LegendComponent,
  type LegendComponentOption,
} from 'echarts/components'
import { PieChart, type PieSeriesOption } from 'echarts/charts'
import { LabelLayout } from 'echarts/features'
import { CanvasRenderer } from 'echarts/renderers'
import { shallowRef } from 'vue'

echarts.use([TooltipComponent, LegendComponent, PieChart, CanvasRenderer, LabelLayout])

type EChartsOption = echarts.ComposeOption<
  TooltipComponentOption | LegendComponentOption | PieSeriesOption
>
// ECharts 实例引用
const chartInstance = shallowRef<echarts.ECharts | null>(null)
export interface IData {
  value: number
  name?: string
}

export class charts {
  // 初始化图表
  static initChart(op: any) {
    const chartDom = document.getElementById('echarts')
    if (chartDom) {
      chartInstance.value = echarts.init(chartDom)
      // 设置初始空图表
      const option = this.SetOption(op)
      chartInstance.value.setOption(option)
    }
  }
  // 更新图表函数
  static updateChart(chartData: IData[]) {
    if (chartInstance.value) {
      const option = this.SetOption(chartData)
      chartInstance.value.setOption(option, { notMerge: true })
    }
  }
  static SetOption(CustomData: IData[] = []) {
    /** @type EChartsOption */
    const option: EChartsOption = {
      tooltip: {
        trigger: 'item',
        show: true,
      },
      legend: {
        top: '5%',
        left: 'center',
        show: false,
      },
      series: [
        {
          // name: 'Access From',
          type: 'pie',
          radius: ['40%', '70%'],
          avoidLabelOverlap: false,
          itemStyle: {
            borderRadius: 10,
            borderColor: '#fff',
            borderWidth: 2,
          },
          label: {
            show: false,
            position: 'center',
          },
          emphasis: {
            label: {
              show: false,
              fontSize: 20,
              fontWeight: 'bold',
            },
          },
          labelLine: {
            show: true,
          },
          // data: [
          //   { value: 1048, name: 'Search Engine' },
          //   { value: 735, name: 'Direct' },
          //   { value: 580, name: 'Email' },
          //   { value: 484, name: 'Union Ads' },
          //   { value: 300, name: 'Video Ads' },
          // ],
          data: CustomData,
        },
      ],
    }
    return option
  }
  // 调整图表大小
  static resizeChart() {
    if (chartInstance.value) {
      chartInstance.value.resize({ animation: { duration: 300 } })
    }
  }
}
